package com.PictureSite.DatabaseAccess;

import java.util.List;

import com.PictureSite.model.UserPost;
import com.google.appengine.api.datastore.DatastoreFailureException;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;

public class PictureSiteCreatePostDAO implements GenericDAO {
	
	private DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

	@Override
	public void storePost(UserPost newPost) {
		Entity picturePost = new Entity("PicturePost");
		try {
			picturePost.setProperty("userName", newPost.getUserName());
			picturePost.setProperty("title", newPost.getTitle());
			picturePost.setProperty("date", newPost.getDatePosted());
			picturePost.setProperty("blobId", newPost.getBlobId());
			
			datastore.put(picturePost);
		} catch (DatastoreFailureException e) {
		}
	}

	@Override
	public List<Entity> getPostByDateDesc(int pageLimit, int pageNumber) {
		Query query = new Query("PicturePost").addSort("date",Query.SortDirection.DESCENDING);
		List<Entity> results;
		
		results = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(pageLimit)
										.offset(pageLimit*(pageNumber-1)));
		return results;
	}

}
